<?php

if (!function_exists('format_cascade')){

    /**
     * 格式化数据：针对级联选择处理数据格式
     * @param $list
     * @param string $value
     * @param string $label
     * @param string $parent_field
     * @return array
     */
    function format_cascade($list,$value='id',$label='title',$parent_field='parent_id')
    {
        $res = [];
        foreach ($list as $key=>$item){
            $res[$key]['value']=$item[$value];
            $res[$key]['label']=$item[$label];
            $res[$key][$parent_field]=$item[$parent_field];
        }
        $res = list_to_tree($res,true,'value',$parent_field,'children');
        return $res;
    }
}

function format_dTree($list,$is_show = true,$pid = 'parent_id')
{
    if($list){
        $new_list = [];
        foreach ($list as $key=>$item){
            $new_list[$key] = $item;
            $new_list[$key]['parentId'] = $item[$pid];
            $new_list[$key]['isLast'] = in_array($item['id'],array_column($list,$pid))?false:true;
            $new_list[$key]['level'] = count(str2arr($item['parent_ids']))+1;
            $new_list[$key]['checkArr'] = [['type'=>0,'isChecked'=>0]];
            if($is_show){
                $new_list[$key]['basicData'] = [
                    'nodeName'=>$item['name'],
                    'editUrl'=>route('d_Action_editAction',['action_id'=>$item['id']]),
                    'deleteUrl'=>route('d_Action_delete',['action_id'=>$item['id']]),
                ];
            }
            unset($new_list[$key][$pid]);
        }
        $list = list_to_tree($new_list,true,'id','parentId','children');
    }

    return $list;
}

function format_selectTree($list,$index=true,$pk = 'id', $pid = 'pid', $child = '_child', $root=0)
{
    foreach ($list as &$item){
        $item['name'] = $item['title'];
        $item['open'] = true;
        $item['checked'] = true;
        unset($item['title']);
    }
    unset($item);
    return list_to_tree($list,$index,$pk, $pid, $child, $root);
}

function format_option($list)
{
    $options = [];
    foreach ($list as $key=>$item){
        $options[] = ['title'=>$item,'value'=>$key];
    }
    return $options;
}

function format_show_images($images)
{
    $options = [];
    foreach ($images as $key=>$item){
        $options[$item] = $item;
    }
    return $options;
}

function format_message_user($input_user)
{
    $users = str2arr($input_user);
    return array_map(function ($value){
        return  preg_replace('/\[[\S]*?\]/','',$value);
    },$users);
}

function format_json($json)
{
    if(!is_json($json)){
        return $json;
    }
    $arr = json_decode($json,true);
    $text = '';
    foreach ($arr as $key=>$value){
        $text .= $key.':'.$value.'<br/>';
    }
    return $text;
}

function format_rule($str)
{
    $arr = array_map(function ($val){
        return str2arr($val,':');
    },str2arr($str));

    return array_column($arr,null,0);
}
